package net.huashitong.ssydt.provider.pk.service;


import net.huashitong.ssydt.exam.entity.vo.BaseQuestion;
import net.huashitong.ssydt.exceptions.ServiceException;
import net.huashitong.ssydt.money.constant.OperationEnum;
import net.huashitong.ssydt.msg.constant.MessageConsts;
import net.huashitong.ssydt.pk.entity.*;
import net.huashitong.ssydt.pk.entity.vo.*;
import net.huashitong.ssydt.provider.exam.service.ExamService;
import net.huashitong.ssydt.provider.money.service.SsMoneyGoldService;
import net.huashitong.ssydt.provider.msg.dto.SsSingleMessage;
import net.huashitong.ssydt.provider.msg.service.MsgPushService;
import net.huashitong.ssydt.provider.task.service.SsTaskMedalRecordService;
import net.huashitong.ssydt.provider.task.service.SsTaskMyCardService;
import net.huashitong.ssydt.provider.task.service.SsTaskMyMedalService;
import net.huashitong.ssydt.provider.user.service.UserService;
import net.huashitong.ssydt.provider.utils.date.DateUtils;
import net.huashitong.ssydt.provider.vo.BaseLongIdPagingVO;
import net.huashitong.ssydt.task.constant.TaskConsts;
import net.huashitong.ssydt.task.entity.SsTaskMedalRecord;
import net.huashitong.ssydt.task.entity.SsTaskMyCard;
import net.huashitong.ssydt.task.entity.SsTaskMyMedal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.12.11
 */
@Service
@Transactional
public class YmdxServiceImpl implements YmdxService {

    private Logger logger = LoggerFactory.getLogger(YmdxService.class);

    private SsPkMyChallengeService ssPkMyChallengeService;

    private SsMoneyGoldService ssMoneyGoldService;

    private SsPkYmdxMatchRecordService ssPkYmdxMatchRecordService;

    private SsPkYmdxQuestionRelationService ssPkYmdxQuestionRelationService;

    private SsPkYmdxChallengeRecordService ssPkYmdxChallengeRecordService;

    private ExamService examService;

    private SsPkYmdxMyRankService ssPkYmdxMyRankService;

    private SsPkYmdxRankService ssPkYmdxRankService;

    private UserService userService;

    private SsPkYmdxMyMedalService ssPkYmdxMyMedalService;

    private SsPkYmdxMedalRankService ssPkYmdxMedalRankService;

    private MsgPushService msgPushService;

    private SsTaskMedalRecordService ssTaskMedalRecordService;

    private SsTaskMyMedalService ssTaskMyMedalService;

    private SsTaskMyCardService ssTaskMyCardService;

    @Autowired
    public YmdxServiceImpl(SsPkMyChallengeService ssPkMyChallengeService,
                           SsMoneyGoldService ssMoneyGoldService,
                           SsPkYmdxMatchRecordService ssPkYmdxMatchRecordService,
                           SsPkYmdxQuestionRelationService ssPkYmdxQuestionRelationService,
                           SsPkYmdxChallengeRecordService ssPkYmdxChallengeRecordService,
                           ExamService examService,
                           SsPkYmdxMyRankService ssPkYmdxMyRankService,
                           SsPkYmdxRankService ssPkYmdxRankService,
                           UserService userService,
                           SsPkYmdxMyMedalService ssPkYmdxMyMedalService,
                           SsPkYmdxMedalRankService ssPkYmdxMedalRankService,
                           MsgPushService msgPushService,
                           SsTaskMedalRecordService ssTaskMedalRecordService,
                           SsTaskMyMedalService ssTaskMyMedalService,
                           SsTaskMyCardService ssTaskMyCardService) {
        this.ssPkMyChallengeService = ssPkMyChallengeService;
        this.ssMoneyGoldService = ssMoneyGoldService;
        this.ssPkYmdxMatchRecordService = ssPkYmdxMatchRecordService;
        this.ssPkYmdxQuestionRelationService = ssPkYmdxQuestionRelationService;
        this.ssPkYmdxChallengeRecordService = ssPkYmdxChallengeRecordService;
        this.examService = examService;
        this.ssPkYmdxMyRankService = ssPkYmdxMyRankService;
        this.ssPkYmdxRankService = ssPkYmdxRankService;
        this.userService = userService;
        this.ssPkYmdxMyMedalService = ssPkYmdxMyMedalService;
        this.ssPkYmdxMedalRankService = ssPkYmdxMedalRankService;
        this.msgPushService = msgPushService;
        this.ssTaskMedalRecordService = ssTaskMedalRecordService;
        this.ssTaskMyMedalService = ssTaskMyMedalService;
        this.ssTaskMyCardService = ssTaskMyCardService;
    }

    @Override
    public GameRuleVO get() {
        SsPkYmdxMatchRecord ssPkYmdxMatchRecord = ssPkYmdxMatchRecordService.getNowYmdxMatch();
        GameRuleVO vo = null;
        if (ssPkYmdxMatchRecord == null) {
            vo = new GameRuleVO();
        } else {
            vo = new GameRuleVO(ssPkYmdxMatchRecord);
        }
        return vo;
    }

    @Override
    public Integer getFree(String userId) {
        SsPkMyChallenge ssPkMyChallenge = ssPkMyChallengeService.getAutoUpdateByUserId(userId);
        return ssPkMyChallenge.getYmdx();
    }

    @Override
    public ChallengeRecordVO postChallenge(String userId) {
        //消耗免费次数或扣金币
        consumeTimesOrGold(userId);
        //取题返回
        List<SsPkYmdxQuestionRelation> ssPkYmdxQuestionRelations = ssPkYmdxQuestionRelationService.findNewest();
        List<BaseQuestion> questions = new ArrayList<>();
        for (SsPkYmdxQuestionRelation ssPkYmdxQuestionRelation : ssPkYmdxQuestionRelations) {
            BaseQuestion question = examService.getBaseQuestion(ssPkYmdxQuestionRelation.getQuestionId());
            questions.add(question);
        }

        SsPkYmdxMatchRecord ssPkYmdxMatchRecord = ssPkYmdxMatchRecordService.getNowYmdxMatch();
        SsPkYmdxChallengeRecord record = new SsPkYmdxChallengeRecord();
        record.setMatchRecordId(ssPkYmdxMatchRecord.getId());
        record.setUserId(userId);
        record.setRemoveErrorTimes(0);
        record.setSelectedCorrectTimes(0);
        record.setIsSubmit((byte) 0);
        record.setTotalScore(BigDecimal.ZERO);
        record.setPaperScore(BigDecimal.ZERO);
        record.setMedalScore(BigDecimal.ZERO);
        record.setCardScore(BigDecimal.ZERO);
        record.setRank(0);
        record.setRiseRank(0);
        record.setGoldNumber(0L);
        ssPkYmdxChallengeRecordService.insertSelective(record);

        ChallengeRecordVO vo = new ChallengeRecordVO(record);
        vo.setQuestions(questions);
        return vo;
    }

    @Override
    public ChallengeRecordVO postChallengeSubmit(ChallengeSubmitVO challengeSubmitVO, String userId) {
        SsPkYmdxChallengeRecord record = ssPkYmdxChallengeRecordService
                .selectByPrimaryKey(challengeSubmitVO.getRecordId());
        if (record == null) {
            throw new ServiceException("挑战记录不存在");
        }
        if (record.getIsSubmit().equals((byte) 1)) {
            return new ChallengeRecordVO(record);
        }
        SsPkYmdxMatchRecord ssPkYmdxMatchRecord = ssPkYmdxMatchRecordService.selectByPrimaryKey(record.getMatchRecordId());
        //统计获得金币数
        long goldNumber = ssPkYmdxMatchRecord.getRightAnswerGold() * challengeSubmitVO.getCorrectNumber();
        //计算勋章加成
        SsTaskMyMedal ssTaskMyMedal = ssTaskMyMedalService.getAutoCreateByUserId(record.getUserId());
        //计算卡包加成
        SsTaskMyCard ssTaskMyCard = ssTaskMyCardService.getAutoCreateByUserId(record.getUserId());
        //卷面成绩
        challengeSubmitVO.setPaperScore(challengeSubmitVO.getPaperScore().setScale(3, BigDecimal.ROUND_DOWN));
        //统计总分
        BigDecimal totalScore = challengeSubmitVO.getPaperScore()
                .add(ssTaskMyMedal.getAddScore())
                .add(ssTaskMyCard.getAddScore());

        //统计排名和变动名次
        //排名
        SsPkYmdxMyRank ssPkYmdxMyRank = ssPkYmdxMyRankService
                .getAutoLoadLastRankByMatchRecordIdWithUserId(record.getMatchRecordId(), userId);
        int oldRanking = ssPkYmdxMyRank.getRanking();
        if (ssPkYmdxMyRank.getHighestScore().compareTo(totalScore) < 0) {
            ssPkYmdxMyRank.setHighestScore(totalScore);
            ssPkYmdxMyRank.setHighestGmtModified(new Date(System.currentTimeMillis()));
        }
        ssPkYmdxMyRank = ssPkYmdxMyRankService.updateRank(ssPkYmdxMyRank);
        //变动名次
        int riseRank = 0;
        if (oldRanking != 0) {
            riseRank = oldRanking - ssPkYmdxMyRank.getRanking();
        }
        //给用户增加金币并记录日志
        if (goldNumber > 0) {
            ssMoneyGoldService.modifyAndRecordBill(userId, OperationEnum.ADD, goldNumber, "一马当先答对题目奖励");
        }

        //保存比赛记录
        record.setIsSubmit((byte) 1);
        record.setMedalScore(ssTaskMyMedal.getAddScore());
        record.setCardScore(ssTaskMyCard.getAddScore());
        record.setTotalScore(totalScore);
        record.setPaperScore(challengeSubmitVO.getPaperScore());
        record.setRank(ssPkYmdxMyRank.getRanking());
        record.setRiseRank(riseRank);
        record.setGoldNumber(goldNumber);
        record.setCorrectNumber(challengeSubmitVO.getCorrectNumber());
        ssPkYmdxChallengeRecordService.updateByPrimaryKeySelective(record);

        //返回数据
        return new ChallengeRecordVO(record);
    }

    @Override
    public int getTimer() {
        long endTime;
        String today = DateUtils.getDate();
        String time = "12:00:00";
        if (DateUtils.getTime().compareTo(time) > 0) {
            endTime = DateUtils.parseDate(String.format("%s %s", DateUtils.getPastDayStr(today, 1), time)).getTime();
        } else {
            endTime = DateUtils.parseDate(String.format("%s %s", today, time)).getTime();
        }
        long timeMillis = endTime - System.currentTimeMillis();
        int timer = 0;
        if (timeMillis > 1000) {
            timer = (int) (timeMillis / 1000);
        }
        return timer;
    }

    @Override
    public void postRemoveError(ChallengePrivilegeVO challengePrivilegeVO, String userId) {
        SsPkYmdxChallengeRecord challengeRecord = ssPkYmdxChallengeRecordService
                .selectByPrimaryKey(challengePrivilegeVO.getRecordId());
        SsPkYmdxMatchRecord ssPkYmdxMatchRecord = ssPkYmdxMatchRecordService.selectByPrimaryKey(challengeRecord.getMatchRecordId());
        Integer removeErrorTimes = challengeRecord.getRemoveErrorTimes();
        int times = challengePrivilegeVO.getTimes() - removeErrorTimes;
        while (times > 0) {
            removeErrorTimes++;
            long goldNumber = ssPkYmdxMatchRecord.getRemoveErrorGold() * removeErrorTimes;
            ssMoneyGoldService.modifyAndRecordBill(userId, OperationEnum.SUBTRACT, goldNumber, "一马当先去除错误答案");
            times--;
        }
        challengeRecord.setRemoveErrorTimes(removeErrorTimes);
        ssPkYmdxChallengeRecordService.updateByPrimaryKey(challengeRecord);

    }

    @Override
    public void postSelectedCorrect(ChallengePrivilegeVO challengePrivilegeVO, String userId) {
        SsPkYmdxChallengeRecord challengeRecord = ssPkYmdxChallengeRecordService
                .selectByPrimaryKey(challengePrivilegeVO.getRecordId());
        SsPkYmdxMatchRecord ssPkYmdxMatchRecord = ssPkYmdxMatchRecordService.selectByPrimaryKey(challengeRecord.getMatchRecordId());
        Integer selectedCorrect = challengeRecord.getSelectedCorrectTimes();
        int times = challengePrivilegeVO.getTimes() - selectedCorrect;
        while (times > 0) {
            selectedCorrect++;
            long goldNumber = ssPkYmdxMatchRecord.getSelectedCorrectGold() * selectedCorrect;
            ssMoneyGoldService.modifyAndRecordBill(userId, OperationEnum.SUBTRACT, goldNumber, "一马当先选中正确答案");
            times--;
        }
        challengeRecord.setSelectedCorrectTimes(selectedCorrect);
        ssPkYmdxChallengeRecordService.updateByPrimaryKey(challengeRecord);
    }

    @Override
    public MyRankVO getMyRank(String userId) {
        SsPkYmdxMatchRecord matchRecord = ssPkYmdxMatchRecordService.getNowYmdxMatch();
        SsPkYmdxMyRank myRank = ssPkYmdxMyRankService.getAutoUpdateRankByMatchRecordIdWithUserId(matchRecord.getId(), userId);
        return new MyRankVO(myRank);
    }

    @Override
    @Scheduled(cron = "0 1/3 * * * ?")
    public void executeRanking() {
        SsPkYmdxMatchRecord matchRecord = ssPkYmdxMatchRecordService.getNowYmdxMatch();
        generateRank(matchRecord.getId());
    }

    @Override
    public List<RankingVO> getRanking(RankingInVO rankingInVO) {
        SsPkYmdxMatchRecord matchRecord = ssPkYmdxMatchRecordService.getNowYmdxMatch();
        rankingInVO.setMatchRecordId(matchRecord.getId());
        List<SsPkYmdxRank> ssPkYmdxRanks = ssPkYmdxRankService.query(rankingInVO);
        List<RankingVO> ranks = new ArrayList<>();
        for (SsPkYmdxRank pkYmdxRank : ssPkYmdxRanks) {
            RankingVO rank = new RankingVO();
            rank.setRanking(pkYmdxRank.getRanking());
            rank.setScore(pkYmdxRank.getScore());
            rank.setUser(userService.getSimpleUser(pkYmdxRank.getUserId()));
            rank.setId(pkYmdxRank.getId());
            ranks.add(rank);
        }
        return ranks;
    }

    @Override
    public MyMedalVO getMyMedal(String userId) {
        int ranking = 0;
        SsPkYmdxMyMedal ssPkYmdxMyMedal = ssPkYmdxMyMedalService.getAutoCreateByUserId(userId);
        SsPkYmdxMedalRank ssPkYmdxMedalRank = ssPkYmdxMedalRankService.getByUserId(userId);
        if (ssPkYmdxMedalRank != null) {
            ranking = ssPkYmdxMedalRank.getRanking();
        }
        MyMedalVO myMedalVO = new MyMedalVO(ssPkYmdxMyMedal);
        myMedalVO.setRanking(ranking);
        return myMedalVO;
    }

    @Override
    public List<MedalVO> getMedalRank(BaseLongIdPagingVO baseLongIdPagingVO) {
        List<MedalVO> list = new ArrayList<>();
        List<SsPkYmdxMedalRank> ssPkYmdxMedalRanks = ssPkYmdxMedalRankService.query(baseLongIdPagingVO);
        for (SsPkYmdxMedalRank ssPkYmdxMedalRank : ssPkYmdxMedalRanks) {
            MedalVO medalVO = new MedalVO(ssPkYmdxMedalRank);
            medalVO.setUser(userService.getSimpleUser(ssPkYmdxMedalRank.getUserId()));
            list.add(medalVO);
        }
        return list;
    }

    @Override
    @Scheduled(cron = "0 5/20 12,14,18 * * ?")
    public void calculateFinalRankAndSettlementNotify() {
        SsPkYmdxRank rank = null;
        List<SsPkYmdxMatchRecord> ssPkYmdxMatchRecords = ssPkYmdxMatchRecordService.findNonFinal();
        for (SsPkYmdxMatchRecord ssPkYmdxMatchRecord : ssPkYmdxMatchRecords) {
            //生成最终排行
            generateRank(ssPkYmdxMatchRecord.getId());
            //用户奖励金币并推送通知
            List<SsPkYmdxRank> ssPkYmdxRanks = ssPkYmdxRankService.findTopTen(ssPkYmdxMatchRecord.getId());
            for (SsPkYmdxRank ssPkYmdxRank : ssPkYmdxRanks) {
                Long goldNumber;
                String description = String.format("一马当先挑战获得第%d名", ssPkYmdxRank.getRanking());
                SsPkYmdxMyMedal ssPkYmdxMyMedal;//更新用户的奖牌
                switch (ssPkYmdxRank.getRanking()) {
                    case 1:
                        goldNumber = ssPkYmdxMatchRecord.getFirstGold();
                        ssPkYmdxMyMedal = ssPkYmdxMyMedalService.getAutoCreateByUserId(ssPkYmdxRank.getUserId());
                        ssPkYmdxMyMedal.setGoldMedal(ssPkYmdxMyMedal.getGoldMedal() + 1);
                        ssPkYmdxMyMedalService.updateByPrimaryKey(ssPkYmdxMyMedal);
                        rank = ssPkYmdxRank;
                        break;
                    case 2:
                        goldNumber = ssPkYmdxMatchRecord.getSecondGold();
                        ssPkYmdxMyMedal = ssPkYmdxMyMedalService.getAutoCreateByUserId(ssPkYmdxRank.getUserId());
                        ssPkYmdxMyMedal.setSilverMedal(ssPkYmdxMyMedal.getSilverMedal() + 1);
                        ssPkYmdxMyMedalService.updateByPrimaryKey(ssPkYmdxMyMedal);
                        break;
                    case 3:
                        goldNumber = ssPkYmdxMatchRecord.getThirdGold();
                        ssPkYmdxMyMedal = ssPkYmdxMyMedalService.getAutoCreateByUserId(ssPkYmdxRank.getUserId());
                        ssPkYmdxMyMedal.setBronzeMedal(ssPkYmdxMyMedal.getBronzeMedal() + 1);
                        ssPkYmdxMyMedalService.updateByPrimaryKey(ssPkYmdxMyMedal);
                        break;
                    default:
                        goldNumber = ssPkYmdxMatchRecord.getFourthToTenthGold();
                        break;
                }
                ssMoneyGoldService.modifyAndRecordBill(ssPkYmdxRank.getUserId(), OperationEnum.ADD, goldNumber, description);

                SsSingleMessage ssSingleMessage = new SsSingleMessage();
                ssSingleMessage.setRecipient(ssPkYmdxRank.getUserId());
                ssSingleMessage.setTitle("一马当先");
                ssSingleMessage.setText(String.format("恭喜您%s，奖励%d金币", description, goldNumber));
                ssSingleMessage.setMsgType(MessageConsts.MsgType.SYSTEM);
                ssSingleMessage.setTargetType(MessageConsts.TargetType.GOLD);
                msgPushService.pushSingleMessage(ssSingleMessage);


            }
            //统计挑战人数
            int participantNumber = ssPkYmdxChallengeRecordService
                    .countDistinctUserIdByMatchRecordId(ssPkYmdxMatchRecord.getId());
            //更新状态
            ssPkYmdxMatchRecord.setParticipantNumber(participantNumber);
            ssPkYmdxMatchRecord.setIsFinal((byte) 1);
            ssPkYmdxMatchRecord.setIsSettlement((byte) 1);
            ssPkYmdxMatchRecordService.updateByPrimaryKey(ssPkYmdxMatchRecord);
        }
        logger.info("一马当先奖励发放成功，影响{}条比赛记录", ssPkYmdxMatchRecords.size());

        //更新奖牌榜
        if (!ssPkYmdxMatchRecords.isEmpty()) {
            this.updateMedalRank();
            updateUserTaskMedal(rank);
        }
    }

    @Override
    public void updateUserTaskMedal(SsPkYmdxRank ssPkYmdxRank) {
        if (ssPkYmdxRank == null) {
            return;
        }
        //连胜勋章
        Long matchRecordId = ssPkYmdxMatchRecordService.getLastMatchRecordId(ssPkYmdxRank.getMatchRecordId());
        SsPkYmdxRank rank = ssPkYmdxRankService.getByMatchRecordIdWithUserId(matchRecordId, ssPkYmdxRank.getUserId());
        if (rank != null && rank.getRanking() == 1) {
            SsTaskMedalRecord medalRecord = ssTaskMedalRecordService
                    .getByUserIdWidthMedalId(ssPkYmdxRank.getUserId(), TaskConsts.Medal.LAINSHENG);
            if (medalRecord == null) {
                medalRecord = new SsTaskMedalRecord();
                medalRecord.setMedalId(TaskConsts.Medal.LAINSHENG);
                medalRecord.setUserId(ssPkYmdxRank.getUserId());
                ssTaskMedalRecordService.saveAndUpdateMyMedal(medalRecord);
            }
        }
        //勤学勋章
        String nowDate = DateUtils.getDate();
        String sevenDayAgo = DateUtils.getPastDayStr(nowDate, -7);
        List<String> userIds = ssPkYmdxChallengeRecordService.findUserIdByQinxue(sevenDayAgo, nowDate);
        for (String userId : userIds) {
            SsTaskMedalRecord medalRecord = new SsTaskMedalRecord();
            medalRecord.setMedalId(TaskConsts.Medal.QINXUE);
            medalRecord.setUserId(userId);
            ssTaskMedalRecordService.saveAndUpdateMyMedal(medalRecord);
        }

        //五星勋章
        List<SsPkYmdxMyMedal> myMedals = ssPkYmdxMyMedalService.findByGoldMedalNumberWithNotInTaskMedal(5);
        for (SsPkYmdxMyMedal myMedal : myMedals) {
            SsTaskMedalRecord medalRecord = new SsTaskMedalRecord();
            medalRecord.setMedalId(TaskConsts.Medal.WUXING);
            medalRecord.setUserId(myMedal.getUserId());
            ssTaskMedalRecordService.saveAndUpdateMyMedal(medalRecord);
        }
        logger.info("一马当先用户勋章发放成功");
    }

    /**
     * 更新奖牌榜
     */
    public void updateMedalRank() {
        List<SsPkYmdxMyMedal> ssPkYmdxMyMedals = ssPkYmdxMyMedalService.findCountMedalRank();
        List<SsPkYmdxMedalRank> ranks = new ArrayList<>();
        int i = 1;
        for (SsPkYmdxMyMedal ssPkYmdxMyMedal : ssPkYmdxMyMedals) {
            SsPkYmdxMedalRank ssPkYmdxMedalRank = new SsPkYmdxMedalRank();
            ssPkYmdxMedalRank.setUserId(ssPkYmdxMyMedal.getUserId());
            ssPkYmdxMedalRank.setGoldMedal(ssPkYmdxMyMedal.getGoldMedal());
            ssPkYmdxMedalRank.setSilverMedal(ssPkYmdxMyMedal.getSilverMedal());
            ssPkYmdxMedalRank.setBronzeMedal(ssPkYmdxMyMedal.getBronzeMedal());
            ssPkYmdxMedalRank.setRanking(i++);
            ranks.add(ssPkYmdxMedalRank);
        }
        int deleteNumber = ssPkYmdxMedalRankService.deleteAll();
        int addNumber = ssPkYmdxMedalRankService.batchInsert(ranks);
        logger.info("更新奖牌榜成功，删除{}条记录，新增{}条记录", deleteNumber, addNumber);
    }

    /**
     * 生成排行榜
     *
     * @param matchRecordId
     */
    private void generateRank(Long matchRecordId) {
        List<SsPkYmdxMyRank> ssPkYmdxMyRanks =
                ssPkYmdxMyRankService.findHighestScoreDescByMatchRecordId(matchRecordId);
        //先删
        int deleteNumber = ssPkYmdxRankService.deleteByMatchRecordId(matchRecordId);
        //后写入
        int i = 1;
        List<SsPkYmdxRank> ssPkYmdxRanks = new ArrayList<>();
        for (SsPkYmdxMyRank ssPkYmdxMyRank : ssPkYmdxMyRanks) {
            SsPkYmdxRank rank = new SsPkYmdxRank();
            rank.setMatchRecordId(matchRecordId);
            rank.setUserId(ssPkYmdxMyRank.getUserId());
            rank.setScore(ssPkYmdxMyRank.getHighestScore());
            rank.setRanking(i++);
            ssPkYmdxRanks.add(rank);
        }
        int batchInsertNumber = ssPkYmdxRankService.batchInsert(ssPkYmdxRanks);
        logger.info("一马当先生成排行榜数据，排行榜删除{}条数据,新增{}条数据", deleteNumber, batchInsertNumber);
    }

    /**
     * 消耗免费次数或扣金币
     *
     * @param userId
     */
    private void consumeTimesOrGold(String userId) {
        SsPkMyChallenge ssPkMyChallenge = ssPkMyChallengeService.getAutoUpdateByUserId(userId);
        if (ssPkMyChallenge.getYmdx() > 0) {
            ssPkMyChallenge.setYmdx(ssPkMyChallenge.getYmdx() - 1);
            ssPkMyChallengeService.updateByPrimaryKey(ssPkMyChallenge);
        } else {
            SsPkYmdxMatchRecord ssPkYmdxMatchRecord = ssPkYmdxMatchRecordService.getNowYmdxMatch();
            ssMoneyGoldService.modifyAndRecordBill(userId, OperationEnum.SUBTRACT,
                    ssPkYmdxMatchRecord.getChallengeGold(), "挑战一马当先");
        }
    }


}
